﻿$(document).ready(Page_Load);

function Page_Load(e) {
    $('.button').button();

    $('[name="btnCreateProject"]').click(function () {
        $.ajax(
            {
                type: "POST",
                async: true,
                url: "default.aspx/CreateProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: CreateProject_Success,
                error: CreateProject_Error
            });
    });
}

function CreateProject_Success(data, textStatus, XMLHttpRequest) {
    $("#dialog-newproject").dialog({
        resizable: false,
        height: 320,
        width: 505,
        modal: true,
        buttons: {
            'Create': function () {
                CreateProject();
            },
            'Cancel': function () {
                $(this).dialog('close');
            }
        },
        close: function () {
            $('input').val("");

            $(".error-container").removeClass("ui-state-error ui-corner-all");
            $(".error").html("");

            $('input').removeClass("ui-state-error");
        }
    });

}

function CreateProject_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "CreateProject", 100);
    alert("An error occurred create the user project. Error: " + XMLHttpRequest);

}

function CreateProject() {
    var projectname = $('#name');
    var projectdescription = $('#description');

    var webMethodParams = JSON.stringify({ ProjectName: projectname.val(), ProjectDescription: projectdescription.val() });

    var bValid = true;

    bValid = bValid && checkLength(projectname, "Project Name", 5);

    if (bValid) {
        $.ajax(
            {
                type: "POST",
                async: true,
                url: "Projects/Projects.aspx/CreateProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: Redirect,
                error: CreateProject_Error
            });
    }
}

function Redirect(data, textStatus, XMLHttpRequest) {
    $("#dialog-newproject").dialog('close');

    location.href = "Projects/Projects.aspx";
}